from sqlalchemy.ext.asyncio import AsyncSession
from typing import List
from config.constant import CommonConstant
from exceptions.exception import ServiceException
from module_admin.entity.vo.common_vo import CrudResponseModel
from module_finance.dao.unitInfo_dao import UnitinfoDao
from module_finance.entity.vo.unitInfo_vo import DeleteUnitinfoModel, UnitinfoModel, UnitinfoPageQueryModel
from utils.common_util import CamelCaseUtil
from utils.excel_util import ExcelUtil


class UnitinfoService:
    """
    填报单位主模块服务层
    """

    @classmethod
    async def get_unitInfo_list_services(
        cls, query_db: AsyncSession, query_object: UnitinfoPageQueryModel, is_page: bool = False
    ):
        """
        获取填报单位主列表信息service

        :param query_db: orm对象
        :param query_object: 查询参数对象
        :param is_page: 是否开启分页
        :return: 填报单位主列表信息对象
        """
        unitInfo_list_result = await UnitinfoDao.get_unitInfo_list(query_db, query_object, is_page)

        return unitInfo_list_result


    @classmethod
    async def add_unitInfo_services(cls, query_db: AsyncSession, page_object: UnitinfoModel):
        """
        新增填报单位主信息service

        :param query_db: orm对象
        :param page_object: 新增填报单位主对象
        :return: 新增填报单位主校验结果
        """
        try:
            await UnitinfoDao.add_unitInfo_dao(query_db, page_object)
            await query_db.commit()
            return CrudResponseModel(is_success=True, message='新增成功')
        except Exception as e:
            await query_db.rollback()
            raise e

    @classmethod
    async def edit_unitInfo_services(cls, query_db: AsyncSession, page_object: UnitinfoModel):
        """
        编辑填报单位主信息service

        :param query_db: orm对象
        :param page_object: 编辑填报单位主对象
        :return: 编辑填报单位主校验结果
        """
        edit_unitInfo = page_object.model_dump(exclude_unset=True, exclude={'create_time', })
        unitInfo_info = await cls.unitInfo_detail_services(query_db, page_object.id)
        if unitInfo_info.id:
            try:
                await UnitinfoDao.edit_unitInfo_dao(query_db, edit_unitInfo)
                await query_db.commit()
                return CrudResponseModel(is_success=True, message='更新成功')
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message='填报单位主不存在')

    @classmethod
    async def delete_unitInfo_services(cls, query_db: AsyncSession, page_object: DeleteUnitinfoModel):
        """
        删除填报单位主信息service

        :param query_db: orm对象
        :param page_object: 删除填报单位主对象
        :return: 删除填报单位主校验结果
        """
        if page_object.ids:
            id_list = page_object.ids.split(',')
            try:
                for id in id_list:
                    await UnitinfoDao.delete_unitInfo_dao(query_db, UnitinfoModel(id=id))
                await query_db.commit()
                return CrudResponseModel(is_success=True, message='删除成功')
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message='传入为空')

    @classmethod
    async def unitInfo_detail_services(cls, query_db: AsyncSession, id: int):
        """
        获取填报单位主详细信息service

        :param query_db: orm对象
        :param id: 
        :return: 对应的信息
        """
        unitInfo = await UnitinfoDao.get_unitInfo_detail_by_id(query_db, id=id)
        if unitInfo:
            result = UnitinfoModel(**CamelCaseUtil.transform_result(unitInfo))
        else:
            result = UnitinfoModel(**dict())

        return result

    @staticmethod
    async def export_unitInfo_list_services(unitInfo_list: List):
        """
        导出填报单位主信息service

        :param unitInfo_list: 填报单位主信息列表
        :return: 填报单位主信息对应excel的二进制数据
        """
        # 创建一个映射字典，将英文键映射到中文键
        mapping_dict = {
            'id': '',
            'guid': '',
            'compname': '',
            'compid': '',
            'year': '',
            'compnamesn': '',
            'compsnid': '',
            'yearupfileGuid': '',
            'yearnowfileGuid': '',
            'leader': '',
            'compId': '',
            'deptId': '',
            'progress': '',
            'status': '',
            'enclosureName': '',
            'department': '',
            'remark': '备注',
            'details': '详情',
            'sort': '排序',
            'createTime': '创建时间',
            'updateTime': '更新时间',
            'enable': '是否启用',
            'isvalid': '是否有效',
            'pjxms': '绩效项目个数',
            'sjjz': '绩效所用资金',
            'preDeptId': '上级单位ID',
            'mainType': '单位类型: 0: 机关单位, 1: 事业单位',
            'nineTable': '九张表导入状态: 0: 未导入, 1:已导入',
            'zpbg': '',
            'downloadTime': '最后一次下载报告时间',
            'verifyStatus': '核查状态',
            'nineResult': '9张表核查结果,0:未核查,1:正常,2:异常',
            'reportResult': '报告核查结果,0:未核查,1:正常,2:异常',
        }
        binary_data = ExcelUtil.export_list2excel(unitInfo_list, mapping_dict)

        return binary_data
